package com.atguigu.gulimall.cart.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.constant.CartConstant;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.cart.feign.ProductFeignService;
import com.atguigu.gulimall.cart.interceptor.CartInterceptor;
import com.atguigu.gulimall.cart.service.CartService;
import com.atguigu.gulimall.cart.to.UserInfoTo;
import com.atguigu.gulimall.cart.vo.CartItemVo;
import com.atguigu.gulimall.cart.vo.CartVo;
import com.atguigu.gulimall.cart.vo.SkuInfoVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

import static com.atguigu.common.constant.CartConstant.CART_PREFIX;

/**
 * @ ClassName CartServiceImpl
 * @ Description TODO
 * @ Author admin
 * @ Date 2021/3/29 15:09
 * @ Version 1.0
 */
@Service
@Slf4j
public class CartServiceImpl implements CartService {


    @Autowired
    private StringRedisTemplate redisTemplate;

//    @Autowired
//    private ThreadPoolExecutor executor;


    @Autowired
    private ProductFeignService productFeignService;

    /**
     * 添加购物车
     * 如果购物车中有该购物项，只需要添加数量即可
     * 如果没有则添加，添加时要合并临时购物车
     *
     * @param skuId
     * @param num
     */
    @Override
    public CartItemVo addCartItem(Long skuId, Integer num) {

        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        //获取当前以当前用户标识为key的hash的操作
        BoundHashOperations<String, Object, Object> ops = getCartItemOps();
        // 判断当前商品是否已经存在购物车
        String cartJson = (String) ops.get(skuId.toString());
        // 1 已经存在购物车，将数据取出并添加商品数量
        if (!StringUtils.isEmpty(cartJson)) {
            //1.1 将json转为对象并将count+
            CartItemVo cartItemVo = JSON.parseObject(cartJson, CartItemVo.class);
            cartItemVo.setCount(cartItemVo.getCount() + num);
            //1.2 将更新后的对象转为json并存入redis
            String jsonString = JSON.toJSONString(cartItemVo);
            ops.put(skuId.toString(), jsonString);
            return cartItemVo;
        } else {
            CartItemVo cartItemVo = new CartItemVo();
            // 2 未存在购物车，则添加新商品
//            CompletableFuture<Void> future1 = CompletableFuture.runAsync(() -> {

                RequestContextHolder.setRequestAttributes(requestAttributes);
                //2.1 远程查询sku基本信息
                R info = productFeignService.info(skuId);
                SkuInfoVo skuInfo = info.getData("skuInfo", new TypeReference<SkuInfoVo>() {
                });
                cartItemVo.setCheck(true);
                cartItemVo.setCount(num);
                cartItemVo.setImage(skuInfo.getSkuDefaultImg());
                cartItemVo.setPrice(skuInfo.getPrice());
                cartItemVo.setSkuId(skuId);
                cartItemVo.setTitle(skuInfo.getSkuTitle());
//            }, executor);

            //2.2 远程查询sku属性组合信息
//            CompletableFuture<Void> future2 = CompletableFuture.runAsync(() -> {
                RequestContextHolder.setRequestAttributes(requestAttributes);
                List<String> attrValuesAsString = productFeignService.getSkuSaleAttrValuesAsString(skuId);
                cartItemVo.setSkuAttrValues(attrValuesAsString);
//            }, executor);

//            try {
//                CompletableFuture.allOf(future1, future2).get();
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            } catch (ExecutionException e) {
//                e.printStackTrace();
//            }
            //2.3 将该属性封装并存入redis,登录用户使用userId为key,否则使用user-key
            String toJSONString = JSON.toJSONString(cartItemVo);
            ops.put(skuId.toString(), toJSONString);
            return cartItemVo;
        }
    }

    /**
     * 获取当前用户的cartVo操作对象
     *
     * @return
     */
    private BoundHashOperations<String, Object, Object> getCartItemOps() {
        //先得到当前用户信息
        UserInfoTo userInfoTo = CartInterceptor.toThreadLocal.get();

        String cartKey = "";
        if (userInfoTo.getUserId() != null) {
            //gulimall:cart:1
            cartKey = CART_PREFIX + userInfoTo.getUserId();
        } else {
            cartKey = CART_PREFIX + userInfoTo.getUserKey();
        }

        //绑定指定的key操作Redis
        BoundHashOperations<String, Object, Object> operations = redisTemplate.boundHashOps(cartKey);

        return operations;
    }

    @Override
    public CartItemVo getCartItem(Long skuId) {
        //拿到要操作的购物车信息
        BoundHashOperations<String, Object, Object> cartOps = getCartItemOps();

        String redisValue = (String) cartOps.get(skuId.toString());

        CartItemVo cartItemVo = JSON.parseObject(redisValue, CartItemVo.class);

        return cartItemVo;
    }

    /**
     * @param skuId
     * @param isChecked
     */
    @Override
    public void checkCart(Long skuId, Integer isChecked) {
        CartItemVo cartItem = getCartItem(skuId);
        cartItem.setCheck(isChecked == 1 ? true : false);
        String s = JSON.toJSONString(cartItem);
        BoundHashOperations<String, Object, Object> cartItemOps = getCartItemOps();
        cartItemOps.put(skuId.toString(), s);

    }

    @Override
    public void changeItemCount(Long skuId, Integer num) {
        CartItemVo cartItem = getCartItem(skuId);
        cartItem.setCount(num);
        BoundHashOperations<String, Object, Object> cartItemOps = getCartItemOps();
        String s = JSON.toJSONString(cartItem);
        cartItemOps.put(String.valueOf(skuId), s);
    }

    @Override
    public void deleteItem(Long skuId) {
        BoundHashOperations<String, Object, Object> cartItemOps = getCartItemOps();
        String s = String.valueOf(skuId);
        cartItemOps.delete(s);
    }

    @Override
    public List<CartItemVo> getUserCartItems() {
        //获取当前用户登录的信息
        UserInfoTo userInfoTo = CartInterceptor.toThreadLocal.get();
        if (userInfoTo == null) {
            return null;
        } else {
            String cartKey = CART_PREFIX + userInfoTo.getUserId();
            List<CartItemVo> cartItems = getCartItems(cartKey);
            List<CartItemVo> collect = cartItems.stream().filter(item -> item.getCheck()).map(obj -> {
                //远程调用查询价格
                BigDecimal price = productFeignService.getPrice(obj.getSkuId());
                obj.setPrice(price);
                return obj;
            }).collect(Collectors.toList());
            return collect;
        }
    }

    /**
     * 获取用户登录或者未登录购物车里所有的数据
     *
     * @return
     * @throws ExecutionException
     * @throws InterruptedException
     */
    @Override
    public CartVo getCart() {

        CartVo cartVo = new CartVo();
        UserInfoTo userInfoTo = CartInterceptor.toThreadLocal.get();
        if (userInfoTo.getUserId() != null) {
            //1、登录
            String cartKey = CART_PREFIX + userInfoTo.getUserId();
            //临时购物车的键
            String temptCartKey = CART_PREFIX + userInfoTo.getUserKey();

            //2、如果临时购物车的数据还未进行合并
            List<CartItemVo> tempCartItems = getCartItems(temptCartKey);
            if (tempCartItems != null) {
                //临时购物车有数据需要进行合并操作
                for (CartItemVo item : tempCartItems) {
                    addCartItem(item.getSkuId(), item.getCount());
                }
                //清除临时购物车的数据
                clearCartInfo(temptCartKey);
            }

            //3、获取登录后的购物车数据【包含合并过来的临时购物车的数据和登录后购物车的数据】
            List<CartItemVo> cartItems = getCartItems(cartKey);
            BigDecimal cartVoTotalAmount = getCartVoTotalAmount(cartItems);
            cartVo.setItems(cartItems);
            cartVo.setTotalAmount(cartVoTotalAmount);
        } else {
            //没登录
            String cartKey = CART_PREFIX + userInfoTo.getUserKey();
            //获取临时购物车里面的所有购物项
            List<CartItemVo> cartItems = getCartItems(cartKey);
            BigDecimal cartVoTotalAmount = getCartVoTotalAmount(cartItems);
            cartVo.setItems(cartItems);
            cartVo.setTotalAmount(cartVoTotalAmount);
        }

        return cartVo;
    }

    public BigDecimal getCartVoTotalAmount(List<CartItemVo> cartItems) {
        BigDecimal total = new BigDecimal(0);
        for (CartItemVo cartItem : cartItems) {
            if (cartItem.getCheck()) {
                BigDecimal totalPrice = cartItem.getTotalPrice();
                total = total.add(totalPrice);
            }
        }
        return total;
    }

    /**
     * 清除购物车
     *
     * @param temptCartKey
     */
    private void clearCartInfo(String temptCartKey) {
        redisTemplate.delete(temptCartKey);
    }


    private List<CartItemVo> getCartItems(String cartKey) {
        //获取购物车里面的所有商品
        BoundHashOperations<String, Object, Object> operations = redisTemplate.boundHashOps(cartKey);
        List<Object> values = operations.values();
        if (values != null && values.size() > 0) {
            List<CartItemVo> collect = values.stream().map((obj) -> {
                String str = (String) obj;
                CartItemVo cartItemVo = JSON.parseObject(str, CartItemVo.class);
                return cartItemVo;
            }).collect(Collectors.toList());
            return collect;
        }
        return null;
    }
}
